<?php
// public/materials/edit.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/layout.php';
require_once __DIR__.'/../../includes/flash.php';
require_once __DIR__.'/../../includes/csrf.php';

require_login();
$user = current_user();

// Only admin/hr/trainer can manage
if (!in_array($user['role'], ['admin','hr','trainer'], true)) {
  set_flash('error', 'Access denied.');
  header('Location: index.php');
  exit;
}

global $pdo;
$id = (int)($_GET['id'] ?? 0);

// fetch record
$stmt = $pdo->prepare("SELECT * FROM materials WHERE id=?");
$stmt->execute([$id]);
$material = $stmt->fetch();
if (!$material) {
  set_flash('error', 'Material not found.');
  header('Location: index.php');
  exit;
}

// handle submit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  require_csrf();

  $title = trim($_POST['title']);
  $type = $_POST['type'];
  $training_id = (int)$_POST['training_id'];
  $video_url = $_POST['video_url'] ?? null;

  // If uploading PDF, keep old file if not replaced
  $file_path = $material['file_path'];
  if ($type === 'pdf' && isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
    if ($ext !== 'pdf') {
      set_flash('error', 'Only PDF files allowed.');
      header("Location: edit.php?id=".$id);
      exit;
    }
    $newName = uniqid('mat_').'.pdf';
    $dest = __DIR__.'/../../uploads/'.$newName;
    move_uploaded_file($_FILES['file']['tmp_name'], $dest);
    $file_path = $newName;
  }

  $stmt = $pdo->prepare("UPDATE materials 
                          SET training_id=?, title=?, type=?, file_path=?, video_url=? 
                          WHERE id=?");
  $stmt->execute([$training_id, $title, $type, $file_path, $video_url, $id]);

  set_flash('success', 'Material updated successfully.');
  header("Location: index.php");
  exit;
}

// trainings for dropdown
$trainings = $pdo->query("SELECT id,title FROM trainings ORDER BY title")->fetchAll();

render_header('Edit Material', 'materials');
$flash = get_flash();
if ($flash): ?>
  <div class="alert alert-<?= htmlspecialchars($flash['type']) ?>">
    <?= htmlspecialchars($flash['message']) ?>
  </div>
<?php endif; ?>

<div class="card card-primary">
  <form method="post" enctype="multipart/form-data">
    <?= csrf_field(); ?>
    <div class="card-body">
      <div class="form-group">
        <label>Training</label>
        <select name="training_id" class="form-control" required>
          <?php foreach ($trainings as $t): ?>
            <option value="<?= (int)$t['id'] ?>" <?= $t['id']==$material['training_id']?'selected':'' ?>>
              <?= htmlspecialchars($t['title']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Title</label>
        <input name="title" class="form-control" value="<?= htmlspecialchars($material['title']) ?>" required>
      </div>
      <div class="form-group">
        <label>Type</label>
        <select name="type" class="form-control" id="typeSelect">
          <option value="pdf" <?= $material['type']==='pdf'?'selected':'' ?>>PDF</option>
          <option value="video" <?= $material['type']==='video'?'selected':'' ?>>Video</option>
        </select>
      </div>
      <div class="form-group" id="pdfGroup" style="<?= $material['type']==='pdf'?'':'display:none;' ?>">
        <label>Upload New PDF (leave empty to keep current)</label>
        <input type="file" name="file" class="form-control-file">
        <?php if ($material['file_path']): ?>
          <small>Current: <a target="_blank" href="/ldp/uploads/<?= htmlspecialchars($material['file_path']) ?>">View PDF</a></small>
        <?php endif; ?>
      </div>
      <div class="form-group" id="videoGroup" style="<?= $material['type']==='video'?'':'display:none;' ?>">
        <label>Video URL</label>
        <input name="video_url" class="form-control" value="<?= htmlspecialchars($material['video_url'] ?? '') ?>">
      </div>
    </div>
    <div class="card-footer">
      <button class="btn btn-primary">Update</button>
      <a href="index.php" class="btn btn-secondary">Cancel</a>
    </div>
  </form>
</div>

<script>
document.getElementById('typeSelect').addEventListener('change', function(){
  document.getElementById('pdfGroup').style.display = this.value==='pdf' ? '' : 'none';
  document.getElementById('videoGroup').style.display = this.value==='video' ? '' : 'none';
});
</script>

<?php render_footer(); ?>
